package com.ibeeking.found.msg.rest.service.mq;

import cn.hutool.core.util.ObjectUtil;
import com.ibeeking.found.common.constants.MqConsumerGroup;
import com.ibeeking.found.common.constants.MqTopic;
import com.ibeeking.found.common.entity.msg.EMailSimpleMsgSendParam;
import com.ibeeking.found.common.entity.msg.MsgTemplateParam;
import com.ibeeking.found.common.enums.DefaultEnum;
import com.ibeeking.found.common.enums.sms.MsgChannelEnum;
import com.ibeeking.found.msg.rest.service.IMsgBindConfigService;
import com.ibeeking.found.msg.rest.service.ISendSmsService;
import com.ibeeking.found.msg.rest.service.ISendWxMaMsgService;
import com.ibeeking.found.msg.service.common.param.MsgNoticeParam;
import com.ibeeking.found.msg.service.common.param.SysMsgSendParam;
import com.ibeeking.found.msg.service.common.vo.MsgBindConfigViewVO;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.rocketmq.annotation.MQConsumer;
import com.ibeeking.nematos.rocketmq.base.AbstractMQPushConsumer;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 发送消息
 * @Author ibeeking
 */
@MQConsumer(topic = MqTopic.MSG_NOTICE_TOPIC, consumerGroup = MqConsumerGroup.MSG_NOTICE_GROUP)
public class MsgSendConsumer extends AbstractMQPushConsumer<MsgNoticeParam> {

    @Resource
    private IMsgBindConfigService msgBaseInfoConfigServiceImpl;

    @Autowired
    private NoticeMsgSender noticeMsgSender;

    @Resource
    private ISendWxMaMsgService sendWxMsgServiceImpl;

    @Resource
    private ISendSmsService sendSmsServiceImpl;

    @Override
    public ConsumeConcurrentlyStatus dealMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        for (MessageExt messageExt : list) {
            MsgNoticeParam param = parseMessage(messageExt);
            Map<String, Object> ext = parseExtParam(messageExt);
            if (null != param && !SpringBeanUtil.getBean(MsgSendConsumer.class).process(param, ext)) {
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    @Override
    public boolean process(MsgNoticeParam param, Map<String, Object> map) {
        try {
            if(param == null)  throw new BusinessException("读取参数对象为空！");
            LogUtils.info(">>>>>>>>process Mq Task:{}", JsonUtils.toJsonStr(param));
            String tenantId = param.getTenantId();
            if(StringUtils.isEmpty(tenantId)) throw new BusinessException("读取租户Id为空！");
            String msgChannel = param.getChannel()!=null?param.getChannel():"";
            String templateCode = param.getTemplateCode();
            if(StringUtils.isEmpty(msgChannel) && StringUtils.isEmpty(templateCode))  throw new BusinessException("模板参数和消息类型参数不能同时为空！");
            if(StringUtils.isNotEmpty(templateCode)){
                MsgBindConfigViewVO msgBaseInfoConfig = msgBaseInfoConfigServiceImpl.viewByCode(templateCode);
                if (ObjectUtil.isNull(msgBaseInfoConfig)) {
                    throw new BusinessException("消息信息配置不存在 msgBaseInfo" + templateCode);
                }
                String msgBody = param.getContent();
                if(StringUtils.isEmpty(msgBody)) throw new BusinessException("消息内容不存在!");
                // 是否启用了小程序订阅消息
                Integer maMsgEnable = msgBaseInfoConfig.getMaMsgEnable();
                if (maMsgEnable == DefaultEnum.YES.getValue() || msgChannel.equalsIgnoreCase(MsgChannelEnum.WX_MA_TEMPLATE.name())) {
                    // 调用小程序模板消息发送功能
                    String wxMaTemplateCode = msgBaseInfoConfig.getMaMsgTemplateCode();
                    MsgTemplateParam msgWxMaSendParam = JsonUtils.fromJson(msgBody, MsgTemplateParam.class);
                    noticeMsgSender.sendWxMaTemplateMessage(tenantId, wxMaTemplateCode, msgWxMaSendParam);
                }
                // 是否启用了公众号模板消息
                Integer mpMsgEnable = msgBaseInfoConfig.getMpMsgEnable();
                if (mpMsgEnable == DefaultEnum.YES.getValue() || msgChannel.equalsIgnoreCase(MsgChannelEnum.WX_MP_TEMPLATE.name())) {
                    // 调用公众号消息发送功能
                    String wxMpTemplateCode = msgBaseInfoConfig.getMpMsgTemplateCode();
                    MsgTemplateParam msgWxMpSendParam = JsonUtils.fromJson(msgBody, MsgTemplateParam.class);
                    noticeMsgSender.sendWxMpTemplateMessage(tenantId, wxMpTemplateCode, msgWxMpSendParam);
                }
                // 是否启用了企业微信消息
                Integer cpMsgEnable = msgBaseInfoConfig.getCpMsgEnable();
                if (cpMsgEnable == DefaultEnum.YES.getValue() || msgChannel.equalsIgnoreCase(MsgChannelEnum.WX_CP_MESSAGE.name())) {
                    // 调用企业微消息发送功能
                    String wxCpTemplateCode = msgBaseInfoConfig.getCpMsgTemplateCode();
                    MsgTemplateParam msgWxCpSendParam = JsonUtils.fromJson(msgBody, MsgTemplateParam.class);
                    noticeMsgSender.sendWxCpTemplateMessage(tenantId, wxCpTemplateCode, msgWxCpSendParam);
                }
                // 是否启用了短信消息
                Integer smsMsgEnable = msgBaseInfoConfig.getSmsMsgEnable();
                if (smsMsgEnable == DefaultEnum.YES.getValue() || msgChannel.equalsIgnoreCase(MsgChannelEnum.SMS_TEMPLATE.name())) {
                    // 调用短信消息发送功能
                    String smsTemplateCode = msgBaseInfoConfig.getSmsMsgTemplateCode();
                    MsgTemplateParam smsMsgSendParam = JsonUtils.fromJson(msgBody, MsgTemplateParam.class);
                    noticeMsgSender.sendSmsTemplateMessage(tenantId, smsTemplateCode, smsMsgSendParam);
                }
                // 是否启用了邮件消息
                Integer emailMsgEnable = msgBaseInfoConfig.getEmailMsgEnable();
                if (emailMsgEnable == DefaultEnum.YES.getValue() || msgChannel.equalsIgnoreCase(MsgChannelEnum.EMAIL_TEMPLATE.name())) {
                    // 调用邮件消息发送功能
                    String emailTemplateCode = msgBaseInfoConfig.getEmailMsgTemplateCode();
                    MsgTemplateParam emaialMsgSendParam = JsonUtils.fromJson(msgBody, MsgTemplateParam.class);
                    noticeMsgSender.sendEmailTemplateMessage(tenantId, emailTemplateCode, emaialMsgSendParam);
                }
                // 是否启用了邮件消息
                Integer sysMsgEnable = msgBaseInfoConfig.getSysMsgEnable();
                if (sysMsgEnable == DefaultEnum.YES.getValue()  || msgChannel.equalsIgnoreCase(MsgChannelEnum.SYS_TEMPLATE.name())) {
                    // 调用邮件消息发送功能
                    String sysMsgTemplateCode = msgBaseInfoConfig.getSysMsgTemplateCode();
                    MsgTemplateParam sysMsgSendParam = JsonUtils.fromJson(msgBody, MsgTemplateParam.class);
                    noticeMsgSender.sendSysTemplateMesssage(tenantId, sysMsgTemplateCode, sysMsgSendParam);
                }
                //PasswordCryptor
            }else{
                String msgBody = param.getContent();
                if (MsgChannelEnum.SMS_MESSAGE.name().equals(msgChannel)) {
                    noticeMsgSender.sendSmsSimpleMessage(param);
                } else if (MsgChannelEnum.EMAIL_MESSAGE.name().equals(msgChannel)) {
                    EMailSimpleMsgSendParam emailSimpleSendParam = JsonUtils.fromJson(msgBody, EMailSimpleMsgSendParam.class);
                    noticeMsgSender.sendEmailSimpleMessage(tenantId, emailSimpleSendParam).get();
                }else if (MsgChannelEnum.SYS_MESSAGE.name().equals(msgChannel)) {
                    SysMsgSendParam sysMsgSendParam = JsonUtils.fromJson(msgBody, SysMsgSendParam.class);
                    noticeMsgSender.sendSysSimpleMessage(tenantId, sysMsgSendParam).get();
                }else if (MsgChannelEnum.WX_MP_TEMPLATE.name().equals(msgChannel)) {
                    noticeMsgSender.sendWxMpSimpleMessage(param);
                } else if (MsgChannelEnum.WX_MP_MASS.name().equals(msgChannel)) {
                    noticeMsgSender.sendWxMpMassMessage(param);
                }
            }
            return true;
        } catch (Exception e) {
            LogUtils.error("接收消息通知MQ消息失败：[{}]", param, e);
            return false;
        }
    }
}
